package main

import (
	"fmt"
	"strings"
)

/*
  桥接模式
  例子：设计操作系统的接口，并实现它，同时写两个具体的系统:Windows和Linux
*/

// 操作系统接口
type IOperation interface {
	Boot() //启动
	ExecuteProgram(cmd string) //执行
	SetupProgram(cmd string, program string) //安装
	Build(program string) //构建
}
// 操作系统
type Operation struct {
	reg     map[string]string //命令程序
	validSuffix string //程序后缀
}

func (o *Operation) Boot() {
	o.reg = make(map[string]string)
}

func (o *Operation) ExecuteProgram(cmd string)  {
	program, ok := o.reg[cmd]
	if ok {
		fmt.Println("执行 ", program)
	} else {
		fmt.Println(cmd + " is invalid.")
	}
}

func (o *Operation) SetupProgram(cmd,program string){
	switch o.validSuffix {
	case "*":
		o.reg[cmd] = program
	default:
		if strings.HasSuffix(program, o.validSuffix) {
			o.reg[cmd] = program
		} else {
			fmt.Println("Invalid suffix.")
		}
	}
}

func (o *Operation) Build(program string)  {
	cmd := strings.Trim(program,o.validSuffix)
	//构建完自动安装
	o.SetupProgram(cmd,program)
}


// Windows
type Windows struct {
	Operation
}

// Windows 的启动过程
func (w *Windows) Boot() {
	w.Operation.Boot()
	w.validSuffix = ".exe"
}

// Linux
type Linux struct {
	Operation
}

//	Linux的启动过程
func (l *Linux) Boot() {
	l.Operation.Boot()
	l.validSuffix = "*"
}


func main() {
	// craete windows
	windows := new(Windows)
	windows.Boot()
	// 构建安装
	windows.Build("qq.exe")
	windows.Build("weixin.exe")
	// 运行
	windows.ExecuteProgram("qq")
	windows.ExecuteProgram("weixin")

	// create linux
	linux := new(Linux)
	linux.Boot()
	// 构建安装
	linux.Build("chrome*")
	linux.Build("vim*")
	// 运行
	linux.ExecuteProgram("chrome")
	linux.ExecuteProgram("vim")
}
